//
//  Account.swift
//  微博项目
//
//  Created by admin on 16/3/7.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
let accountFilePath  = "\(NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!)/accountFilePathasdasdasd.plist"
class Account: NSObject,NSCoding {
    // "access_token" = "2.00EEKZiFPE84jC2eec7243aeB3IHeB";
    var access_token:String!
    // "expires_in" = 157679999;
    var expires_in:String!
    // "remind_in" = 157679999;
    var remind_in:String!
    // uid = 5239203116;
    var uid:NSNumber!
    // 单例对象
    class func shareAccount()->Account?{
        struct Singleton{
            static var predicate:dispatch_once_t = 0
            static var instance:Account? = nil
        }
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountFilePath)
        if account != nil
        {
            dispatch_once(&Singleton.predicate,{
                
                    Singleton.instance = account as! Account
                }
            )
        }
        return Singleton.instance
    }
    class func requestAccountWithCode(code:String ,success:(account:Account?)->(Void),faild:(task:NSURLSessionDataTask?, error:NSError) -> Void)
    {
        let paremeters:AccessTokenRequest = AccessTokenRequest(code: code)
        Http.Post("https://api.weibo.com/oauth2/access_token", parameters: paremeters.mj_keyValues(), success: { (task:NSURLSessionDataTask, data:AnyObject?) -> Void in
                let account = Account.mj_objectWithKeyValues(data)
                NSKeyedArchiver.archiveRootObject(account, toFile: accountFilePath)
                success(account: account)
            }) { (task:NSURLSessionDataTask?, error:NSError) -> Void in
                faild(task: task, error: error)
        }
    }
    // 协议的写入数据的方法
    @objc func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.access_token, forKey: "access_token")
        aCoder.encodeObject(self.expires_in, forKey: "expires_in")
        aCoder.encodeObject(self.remind_in, forKey: "remind_in")
        aCoder.encodeObject(self.uid , forKey: "uid")
    }
    // 协议的读取数据的方法
    @objc required init?(coder aDecoder: NSCoder) {
        self.access_token = aDecoder.decodeObjectForKey("access_token") as! String
        self.expires_in = aDecoder.decodeObjectForKey("expires_in") as! String
        self.remind_in = aDecoder.decodeObjectForKey("remind_in") as! String
        self.uid = aDecoder.decodeObjectForKey("uid") as! NSNumber
    }
    override init() {
        super.init()
    }
}